package pub.cleangao.mqtt;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import pub.cleangao.mqtt.processor.Processor;
import pub.cleangao.mqtt.processor.ProcessorFactory;

public class MqttMessageListener implements MqttCallback {

    private final MqttServer mqttServer;

    public MqttMessageListener(MqttServer server) {
        this.mqttServer = server;
    }


    @Override
    public void connectionLost(Throwable throwable) {
        System.out.println("与服务器断开连接，尝试重连");
        mqttServer.reconnect();
    }

    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        int start = topic.indexOf("/");
        int end = topic.indexOf("/", start + 1);
        String serialNo = topic.substring(start + 1, end);
        topic = topic.replace(serialNo, "+");
        Processor processor = ProcessorFactory.getProcessor(topic);
        if (processor == null) {
            return;
        }
        processor.setSerialNo(serialNo);
        processor.process(new String(mqttMessage.getPayload()));

    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

    }
}
